//
//  NTESMediaCapture.m
//  Netease
//
//  Created by 王方伟 on 2017/8/24.
//  Copyright © 2017年 wfw. All rights reserved.
//

#import "NTESMediaCapture.h"
#import "NTESLiveManager.h"
#import "NTESUserUtil.h"
#import "SHDragView.h"

@interface NTESMediaCapture ()
@property (assign, nonatomic) NIMNetCallCamera cameraType;
@property (strong, nonatomic) UIView *containerView;
@property (strong, nonatomic) UIView *displayView;
@end

@implementation NTESMediaCapture
NIMNetCallMeeting *_currentMeeting;

- (instancetype)init{
    self = [super init];
    if (self) {
        _cameraType = NIMNetCallCameraFront;
        __weak typeof(self) wself = self;
        _videoHandler = ^(CMSampleBufferRef sampleBuffer) {
            [wself processVideoSampleBuffer:sampleBuffer];
        };
    }
    return self;
}

- (void)processVideoSampleBuffer:(CMSampleBufferRef)sampleBuffer{
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    size_t bufferWidth = 0;
    size_t bufferHeight = 0;
    
    if (CVPixelBufferIsPlanar(pixelBuffer)) {
        bufferHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
        bufferWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
    } else {
        bufferWidth = CVPixelBufferGetWidth(pixelBuffer);
        bufferHeight = CVPixelBufferGetHeight(pixelBuffer);
    }
    
    if ([NTESLiveManager sharedLiveManager].orientation == NIMVideoOrientationLandscapeRight) {
        if (bufferWidth < bufferHeight) {
            SHLog(@"bufferWidth < bufferHeight");
            return;
        }
    }
    
    [[NIMAVChatSDK sharedSDK].netCallManager sendVideoSampleBuffer:sampleBuffer];
    
}

#pragma mark 视频预览
- (void)startPreview:(NIMNetCallMediaType)type container:(UIView *)container handler:(void (^)(NSError *))handler{
    self.containerView  = container;
    __weak typeof(self) weakSelf = self;
    [NTESUserUtil requestMediaCapturerAccess:type handler:^(NSError *error) {
        handler(error);
        if (!error) {
            if(type == NIMNetCallMediaTypeVideo){
                NIMNetCallVideoCaptureParam *param = [NTESUserUtil videoCaptureParam];
                param.videoHandler = weakSelf.videoHandler;
                BOOL isSuccess = [[NIMAVChatSDK sharedSDK].netCallManager startVideoCapture:param];
                SHLog(@"%d", isSuccess);
            }
        }
    }];
}

- (void)startLiveStreamHandler:(NIMNetCallMeetingHandler)handler{
    if (!self.isLiveStream) {
        self.isLiveStream = YES;
        __weak typeof(self) weakSelf = self;
        
        [[NIMAVChatSDK sharedSDK].netCallManager joinMeeting:_currentMeeting completion:^(NIMNetCallMeeting * _Nonnull meeting, NSError * _Nonnull error) {
            SHLog(@"join meeting error: %@",error);
            if (!error){
                [[NIMAVChatSDK sharedSDK].netCallManager setSpeaker:YES];
            }
            weakSelf.isLiveStream = !error;
            _currentMeeting = meeting;
            if (handler) {
                handler(meeting,error);
            }
        }];
    }else{
        SHLog(@"stream is already start");
        if (handler) {
            NSError * error = [NSError errorWithDomain:@"startLiveHandler" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"stream is already start"}];
            handler(_currentMeeting,error);
        }
    }
}

#pragma mark 停止采集
- (void)stopVideoCapture{
    [[NIMAVChatSDK sharedSDK].netCallManager stopVideoCapture];
}

#pragma mark 旋转摄像头
- (void)switchCamera{
    if (self.cameraType == NIMNetCallCameraFront) {
        self.cameraType = NIMNetCallCameraBack;
    }else{
        self.cameraType = NIMNetCallCameraFront;
    }
    [[NIMAVChatSDK sharedSDK].netCallManager switchCamera:self.cameraType];
    
}

#pragma mark 摄像头画面回调
- (void)onLocalDisplayviewReady:(UIView *)displayView{
    self.displayView = displayView;
    [self setUpDisplayView];
}


-(void)switchContainerToView:(UIView *)captureView{
    self.containerView = captureView;
    if ([NTESLiveManager sharedLiveManager].orientation == NIMVideoOrientationLandscapeRight) {
        self.displayView.hidden = YES;
    }
    
    [self setUpDisplayView];
    
}

- (void)setMeeting:(NIMNetCallMeeting*)meeting{
    _currentMeeting = meeting;
}

- (void)setUpDisplayView{
    
    CGRect frame = self.containerView.bounds;
    
    CGRect displayViewframe = frame;
    self.displayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    self.displayView.frame = displayViewframe;
    
    [self.containerView.superview addSubview:self.displayView];
}

- (void)stopLiveStream{
    if (_currentMeeting) {
        [[NIMAVChatSDK sharedSDK].netCallManager leaveMeeting:_currentMeeting];
        self.isLiveStream = NO;
    }
}

- (BOOL)isCameraBack{
    return self.cameraType == NIMNetCallCameraBack;
}
@end
